import * as vscode from 'vscode';
import * as openers from '../openers';
import * as gitLabService from '../gitlab_service';
import { gitExtensionWrapper } from '../git/git_extension_wrapper';

type VisibilityItem = vscode.QuickPickItem & { type: string };

const PRIVATE_VISIBILITY_ITEM: VisibilityItem = {
  label: '$(lock) 私有',
  type: 'private',
  description: '创建私有笔记',
};

const PUBLIC_VISIBILITY_ITEM: VisibilityItem = {
  label: '$(globe) 公开',
  type: 'public',
  description: '创建公开笔记',
};

export const VISIBILITY_OPTIONS = [PRIVATE_VISIBILITY_ITEM, PUBLIC_VISIBILITY_ITEM];


async function uploadNote(
  editor: vscode.TextEditor,
  visibility: string,
  title?: string
) {
  let content = '';
  const fileName = editor.document.fileName.split('/').reverse()[0];

  const { start, end } = editor.selection;

  if (start.line === end.line) {
    await vscode.window.showInformationMessage('CSDN Workflow: 您未选取任何内容');
    return;
  }

  const repository = await gitExtensionWrapper.getActiveRepositoryOrSelectOne();
  const fileAbsPath = editor.document.uri.path
  let fileRelativePath
  if (repository && fileAbsPath.indexOf(repository.rootFsPath)!==-1) {
    fileRelativePath = fileAbsPath.replace(repository.rootFsPath, ".")
  }

  const noteTitle = `${fileRelativePath || fileName}#L${start.line}-${end.line}`

  const endLine = end.line + 1;
  const startPos = new vscode.Position(start.line, 0);
  const endPos = new vscode.Position(endLine, 0);
  const range = new vscode.Range(startPos, endPos);
  content = editor.document.getText(range);

  const data = {
    title: title || noteTitle,
    description: noteTitle,
    file_name: fileName,
    visibility,
    content,
  };

  const note = await gitLabService.createNote(data);

  await openers.openSnippet(note.id);
}
/**
 *
 */

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export async function createNote() {
  const editor = vscode.window.activeTextEditor;

  if (!editor) {
    await vscode.window.showInformationMessage('CSDN Workflow: 您需要先打开文件然后选中要添加到笔记的内容，才能执行保存笔记的操作');
    return;
  }

  const title = await vscode.window.showInputBox({
    ignoreFocusOut: true,
    placeHolder: 'E.g. 图片上传-update.js',
    prompt: '代码笔记标题',
  });

  const visibility = await vscode.window.showQuickPick(VISIBILITY_OPTIONS);
  if (!visibility) return;

  await uploadNote(editor, visibility.type, title);
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export async function newNoteTextDocument() {
  const sampleText = `/**
  * 您可在此处书写全新的笔记，然后选择需要保存的内容，执行快捷键：shift+alt+j 保存笔记；
  * 也可以在其他已存在内容的文件中，选择要保存的内容，执行快捷键：shift+alt+j 保存笔记。
  */
 `
  const doc = await vscode.workspace.openTextDocument({ language: 'plaintext', content: sampleText });
  await vscode.window.showTextDocument(doc);
}
